package com.vita.common;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.logging.Logger;

public class FileUtils {
    public static final Logger log = Logger.getLogger("FileUtils");

    public static boolean isTxtFile(String fileName){
        return fileName.endsWith(".txt")
                || fileName.endsWith(".TXT");
    }

    public static boolean isXlsFile(String fileName){
        return fileName.endsWith(".xls")
                || fileName.endsWith(".XLS")
                || fileName.endsWith(".xlsx")
                || fileName.endsWith(".XLSX");
    }

    public static boolean isPdfFile(String fileName){
        return fileName.endsWith(".PDF")
                || fileName.endsWith(".pdf");
    }

    public static boolean isCsvFile(String fileName) {
        return fileName.endsWith(".CSV")
                || fileName.endsWith(".csv");
    }

    /**
     * 按行读取文件
     */
    public static List<String> getList(String fileName){
        List<String> lines = null;
        try {
            lines = Files.readAllLines(Paths.get(fileName),
                    StandardCharsets.UTF_8);
        }catch (NoSuchFileException noFile){
            log.info("文本转换器>>> 找不到文件"+fileName);
        }catch (IOException e){
            log.info("文本转换器>>> 文件读取中产生异常: "+e.getMessage());
        }
        return lines;
    }

    public static void writeList(String filename,List<String> list){
        try{
            Files.write(Paths.get(filename), "".getBytes());
        }catch (IOException ignored){}

        list.forEach(s-> {
            try {
                Files.write(Paths.get(filename), (s+"\n").getBytes(), StandardOpenOption.APPEND);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }
}
